<?php

namespace App\Service\College;

use App\Models\College\CollegeTrainingOrderLogModel;
use App\Models\College\CollegeTrainingOrderModel;
use App\Models\College\CollegeTrainingOrderUserModel;
use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Service\BaseService;
use App\Service\Cruise\Mission\CollegeInputService;
use App\Service\OpenShop\User\RmsUserService;
use Illuminate\Support\Facades\DB;

class CollegeExamService extends BaseService
{
    public static function lists(int $pageNum, int $pageSize, int $userId, int $shopId): array
    {
        $paginator = CollegeTrainingOrderModel::query()
                                              ->with('planRel')
                                              ->join('college_training_order_users as user',
                                                  'college_training_orders.id', '=',
                                                  'user.trainingOrderId')
                                              ->where('user.userId', $userId)
                                              ->where('user.isDeleted', 0)
                                              ->where('studentShopId', $shopId)
                                              ->where('college_training_orders.planId', '>', 0)
                                              ->whereIn('college_training_orders.status', [CollegeTrainingOrderModel::STATUS_ING, CollegeTrainingOrderModel::STATUS_WAIT_UPLOAD, CollegeTrainingOrderModel::STATUS_FINISH])
                                              ->select([
                                                  'user.*',
                                                  'college_training_orders.orderNo',
                                                  'college_training_orders.planId',
                                                  DB::raw('(user.examResult=0) as waitFinish')
                                              ])
                                              ->orderByDesc('waitFinish')
                                              ->orderByDesc('id')
                                              ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $userIds   = collect($paginator->items())->pluck('userId')->toArray();
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'] ?? [])->keyBy('id');

        return BaseService::pageLists($paginator, function ($item) use ($userInfos) {

            $status = $item->finalResult;
            if (in_array($status,
                [CollegeTrainingOrderUserModel::RESULT_OK, CollegeTrainingOrderUserModel::RESULT_FAIL])) {
                $status     = CollegeTrainingOrderUserModel::RESULT_OK;
                $statusText = '已完成';
            } else {
                $statusText = CollegeTrainingOrderUserModel::EXAM_RESULT_TEXT[$item->finalResult] ?? '';
            }

            return [
                'cruiseOrderId'    => $item->cruiseOrderId,
                'name'             => $item->planRel->name ?? '',
                'status'           => $status,
                'statusText'       => $statusText,
                'orderNo'          => $item->orderNo,
                'examNo'           => $item->examNo,
                'courseStartTime'  => $item->planRel->courseStartTime ?? '',
                'userName'         => $userInfos[$item->userId]['username'] ?? '',
                'userAvatar'       => $userInfos[$item->userId]['avatar'] ?? '',
                'examActualScore'  => $item->examActualScore,
                'examTotalScore'   => $item->examTotalScore,
                'examSuccessScore' => (int)($item->examTotalScore * CollegeInputService::EXAM_SUCCESS_RATE),
                'examQuestionNum'  => $item->examQuestionNum,
                'examDuration'     => CollegeInputService::EXAM_DURATION,
                'examResult'       => $item->examResult,
                'examResultText'   => CollegeTrainingOrderUserModel::EXAM_RESULT_TEXT[$item->examResult] ?? '',

                'successImgs' => ((array)ResourcesModel::getModuleBusinessResources(
                        ResourcesModel::MODULE_TYPE_COLLEGE,
                        ResourcesModel::BUSINESS_COLLEGE_COURSES,
                        13,
                        ['trainCompleteImg']
                    ))['trainCompleteImg'] ?? [],

                'failImgs' => ((array)ResourcesModel::getModuleBusinessResources(
                        ResourcesModel::MODULE_TYPE_COLLEGE,
                        ResourcesModel::BUSINESS_COLLEGE_COURSES,
                        $item->id,
                        ['failLetter']
                    ))['failLetter'] ?? [],
            ];
        });
    }

    /**
     * 生成每个用户的试卷
     * @param int $shopId
     * @param int $trainingOrderId
     * @param array $userIds
     * @return void
     */
    public static function initExam(CollegeTrainingOrderModel $collegeTrainingOrderModel): void
    {
        $collegeTrainingOrderModel->userRel->each(function ($item) use ($collegeTrainingOrderModel) {

            // 已生成 - 幂等
            if ($item->cruiseOrderId) {
                return;
            }

            //添加订单表
            $cruiseOrder             = new CruiseOrderModel();
            $cruiseOrder->orderNo    = (string)OpenShopMainProcessModel::query()
                                                                       ->where('shopId',
                                                                           $collegeTrainingOrderModel->studentShopId)
                                                                       ->value('orderNo');
            $cruiseOrder->shopId     = $collegeTrainingOrderModel->studentShopId;
            $cruiseOrder->type       = CruiseTemplateModel::TYPE_4;
            $cruiseOrder->status     = CruiseOrderModel::STATUS_INIT;
            $cruiseOrder->handlerId  = $item->userId;
            $cruiseOrder->templateId = CruiseTemplateModel::getTemplateIdBySysTemplate(CruiseTemplateModel::SYS_TEMPLATE_COLLEGE);
            $cruiseOrder->save();

            // 更新关联表id
            $item->cruiseOrderId = $cruiseOrder->id;
            $item->save();

            // 生成试卷input
            $obj = (new CollegeInputService($cruiseOrder->id));
            $obj->initOrderInput(false);

            // 题目数量
            list($examTotalScore, $examActualScore, $_, $_, $examQuestionNum) = $obj->scores();
            $item->examQuestionNum = $examQuestionNum;
            $item->examActualScore = $examActualScore;
            $item->examTotalScore  = $examTotalScore;
            $item->save();
        });
    }
}
